package com.lai.service;


import com.lai.dao.WalletMapper;
import com.lai.pojo.Transaction;
import com.lai.pojo.enumeration.TransactionType;
import org.apache.ibatis.annotations.Param;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import java.math.BigDecimal;
import java.util.List;
import java.util.Random;


public class WalletMapperImpl extends SqlSessionDaoSupport implements WalletMapper {

    private SqlSessionTemplate sqlSession;
    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }


    public void spendFromWallet(@Param("userId") int userId, @Param("amount") BigDecimal amount) {
        // 参数校验
        if (amount.compareTo(BigDecimal.ZERO) < 0) {
            throw new IllegalArgumentException("金额不能为负数");
        }
        sqlSession.getMapper(WalletMapper.class).spendFromWallet(userId, amount);
        addTransaction(new Transaction(new Random().nextInt(),userId,amount, TransactionType.PURCHASE));
    }

    public void refundToWallet(@Param("userId") int userId,@Param("amount") BigDecimal amount) {
        // 参数校验
        if (amount.compareTo(BigDecimal.ZERO) < 0) {
            throw new IllegalArgumentException("金额不能为负数");
        }
        sqlSession.getMapper(WalletMapper.class).refundToWallet(userId, amount);
        addTransaction(new Transaction(new Random().nextInt(),userId,amount, TransactionType.REFUND));
    }

    public BigDecimal selectBalanceById(int userId) {
        BigDecimal balance = sqlSession.getMapper(WalletMapper.class).selectBalanceById(userId);
        return balance != null ? balance : BigDecimal.ZERO;
    }

    public void addTransaction(Transaction transaction) {
        sqlSession.getMapper(WalletMapper.class).addTransaction(transaction);
    }

    public List<Transaction> selectTransaction(int userId) {
        return sqlSession.getMapper(WalletMapper.class).selectTransaction(userId);
    }


}
